﻿using System;
using System.Diagnostics.Contracts;
using System.Linq;
using CardPlay.Model.ActionModel;

namespace CardPlay.Model.GameModel.Actions
{
    public class CollectTableauAction : ComplexAction
    {
        public CollectTableauAction(CardGame cardGame, PartLocation targetLocation)
        {
            Contract.Requires<ArgumentNullException>(cardGame != null, "game");

            var topLocations = cardGame
                .PilesNamed(CardGame.AnyTableau)
                .Where(pile => ! pile.IsEmpty)
                .Select(pile => pile.Top)
                .ToList();

            while (topLocations.Count > 0)
            {
                var i = topLocations.Count;

                while (i > 0)
                {
                    var sourceLocation = topLocations[--i];

                    if (cardGame.CardAt(sourceLocation).IsFaceUp)
                        Add(new FlipCardAction(cardGame, sourceLocation));

                    ++targetLocation.Index;
                    Add(new MoveCardAction(cardGame, sourceLocation, targetLocation));

                    if (sourceLocation.Index > 0)
                        topLocations[i] = sourceLocation.PreviousLocation;
                    else
                        topLocations.RemoveAt(i);
                }
            }
        }
    }
}